package management

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"reflect"
	"strconv"
	"time"

	"github.com/gorilla/mux"
	"github.com/jsrccb/nachuan/common"
	"github.com/tealeg/xlsx"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/x/bsonx"
)

func initCollMgrApi(r *mux.Router) {

	s := r.PathPrefix("/coll").Subrouter()
	// s.HandleFunc("/list", UserListHandler)
	s.HandleFunc("/updsave", handleCollSave)
	s.HandleFunc("/updconfirm", handleCollConfirm)
	s.HandleFunc("/download", handleDownloadCollInfo)
	s.HandleFunc("/delbyid", handleDelCollById)
	//请求/order/handleOrderqueryall?ordertype=xxx&skip=1&limit=1
	s.HandleFunc("/query", handleCollQuery)

	s.HandleFunc("/opercollfloor", handleOperatingCollFloor)
	// ents := r.PathPrefix("/agentcustomevent").Subrouter()
	// ents.HandleFunc("/queryall", handleOrderEventqueryall)
}
func handleOperatingCollFloor(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entcluests  string
		// custommgr string
		// rolelimit     *common.RoleLimits

		collsumtoday   float64 //今天待追踪
		collcounttoday int32
		collcountmon   int32
		collsummon     float64 //今日线索

	)
	cluemap := make(map[string]interface{})
	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	// custommgr = req.PostForm.Get("custommgr")

	if collcounttoday, collsumtoday, err = G_CollMgr.getOperSumToday(); err != nil {
		goto ERR
	}
	if collcountmon, collsummon, err = G_CollMgr.getOperSumMon(); err != nil {
		goto ERR
	}
	cluemap["collsumtoday"] = collsumtoday
	cluemap["collsummon"] = collsummon
	cluemap["collcounttoday"] = collcounttoday
	cluemap["collcountmon"] = collcountmon

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (collMgr *CollMgr) getOperSumToday() (collcount int32, collsumtoday float64, err error) {

	var (
		ctx     context.Context
		results []bson.M
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	// fmt.Println(common.BuildDateTodayStr2())
	pipeline := mongo.Pipeline{

		{{"$match", bson.D{{"transfeTime", bsonx.Regex(common.BuildDateTodayStr2(), "im")}}}},
		{{"$group", bson.D{{"_id", "floorvalue"}, {"count", bson.D{{"$sum", 1}}}, {"sum", bson.D{{"$sum", "$collVal"}}}}}},

		// {{"$group", bson.D{{"_id", "$accounter"}, {"count", bson.D{{"$sum", 1}}}}}},
		// {{"$group", bson.D{{"_id", "$accounter"}, {"sum", bson.D{{"$sum", "$collVal"}}}}}},
		// {{"$match", bson.D{{"clueNo", bson.M{"$regex": common.BuildDateTodayStr()}}}}},
		// {{"$match", bson.D{{"clueNo", bson.D{"$regex", "2012"}}}}},
	}

	cursor, err := G_CollMgr.CollColl.Aggregate(ctx, pipeline)
	// fmt.Println(err.Error())
	defer cursor.Close(ctx)

	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}
	// fmt.Println(results)

	if results != nil {
		for _, result := range results {
			collsumtoday = result["sum"].(float64)
			collcount = result["count"].(int32)
		}
	} else {
		collsumtoday = 0
		collcount = 0
	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (collMgr *CollMgr) getOperSumMon() (collcount int32, collsumtoday float64, err error) {

	var (
		ctx     context.Context
		results []bson.M
	)
	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	fmt.Println(common.BuildDateMonStr2())
	pipeline := mongo.Pipeline{

		{{"$match", bson.D{{"transfeTime", bsonx.Regex(common.BuildDateMonStr2(), "im")}}}},
		{{"$group", bson.D{{"_id", "floorvalue"}, {"count", bson.D{{"$sum", 1}}}, {"sum", bson.D{{"$sum", "$collVal"}}}}}},

		// {{"$group", bson.D{{"_id", "$accounter"}, {"count", bson.D{{"$sum", 1}}}}}},
		// {{"$group", bson.D{{"_id", "$accounter"}, {"sum", bson.D{{"$sum", "$collVal"}}}}}},
		// {{"$match", bson.D{{"clueNo", bson.M{"$regex": common.BuildDateTodayStr()}}}}},
		// {{"$match", bson.D{{"clueNo", bson.D{"$regex", "2012"}}}}},
	}

	cursor, err := G_CollMgr.CollColl.Aggregate(ctx, pipeline)
	// fmt.Println(err.Error())
	defer cursor.Close(ctx)

	if err = cursor.All(context.TODO(), &results); err != nil {
		log.Fatal(err)
	}
	// fmt.Println(results)

	if results != nil {
		for _, result := range results {
			collsumtoday = result["sum"].(float64)
			collcount = result["count"].(int32)
		}
	} else {
		collsumtoday = 0
		collcount = 0
	}

	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

type CollMgr struct {
	client   *mongo.Client
	CollColl *mongo.Collection
}

var (
	G_CollMgr *CollMgr
)

func handleDelCollById(resp http.ResponseWriter, req *http.Request) {
	var (
		err    error
		bytes  []byte
		collId string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	collId = req.PostForm.Get("collid")

	if err = G_CollMgr.delCollById(collId); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "收款状态删除成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	// fmt.Println(cluein
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCollConfirm(resp http.ResponseWriter, req *http.Request) {
	var (
		err    error
		bytes  []byte
		collId string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	collId = req.PostForm.Get("collid")

	if err = G_CollMgr.updConfirmbyCollId(collId); err == nil {
		if bytes, err = common.BuildResponse(0, "success", "收款状态更新成功"); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	// fmt.Println(cluein
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCollSave(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		coll        *common.Collection
		collinfostr string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	collinfostr = req.PostForm.Get("collinfo")

	if err = json.Unmarshal([]byte(collinfostr), &coll); err != nil {
		goto ERR
	}

	if err = G_CollMgr.saveColl(coll); err == nil {
		if bytes, err = common.BuildResponse(0, "success", coll); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	// fmt.Println(cluein
	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleCollUpd(resp http.ResponseWriter, req *http.Request) {
	var (
		err         error
		bytes       []byte
		coll        *common.Collection
		collinfostr string
		// rolelimit     *common.RoleLimits
	)

	if err = req.ParseForm(); err != nil {
		goto ERR
	}
	collinfostr = req.PostForm.Get("collinfo")

	if err = json.Unmarshal([]byte(collinfostr), &coll); err != nil {
		goto ERR
	}

	if err = G_CollMgr.saveColl(coll); err == nil {
		if bytes, err = common.BuildResponse(0, "success", coll); err == nil {
			resp.Write(bytes)
		}
	} else {
		goto ERR
	}
	// fmt.Println(cluein

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func handleDownloadCollInfo(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet  []bson.M
		collinfos []*common.Collection
		collinfo  *common.Collection
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		collfromtype         string //收款来源类型  订单、客户（用来区分是订单收款还是客户收款）
		collno               string //收款编号  订单编号或者代账客户管理里面的客户编号
		collfrom             string //收款来源 根据订单类别分别显示为：代账客户、注册代账订单、迁入订单、变更订单、注销订单、商标订单、建筑资质订单、其他订单
		collkind             string //收款方式 必选选项，选项分为：建行龙支付、纳川对公、润盈对公、氢数对公、好易标对公、润禾对公、企业支付宝、其他账户
		collstatus           string //转账状态 出纳录入成功显示“出纳已确认”、内账会计角色确认ok则显示“内账会计已确认”
		custommgr            string //客户经理
		accountant           string //主管会计
		beginagentfeeenddate string //代账费开始日期
		endagentfeeenddate   string //代账费结束日期
		begintransfetime     string
		endtransfetime       string
		begincolltime        string
		endcolltime          string
		outfile              string

		x   interface{}
		row *xlsx.Row
	)

	query := req.URL.Query()
	collfromtype = query.Get("collfromtype")
	collno = query.Get("collno")
	collfrom = query.Get("collfrom")
	collkind = query.Get("collkind")
	collstatus = query.Get("collstatus")
	accountant = query.Get("accountant")
	custommgr = query.Get("custommgr")
	// colltime = query.Get("colltime")

	begincolltime = query.Get("begincolltime")
	endcolltime = query.Get("endcolltime")

	begintransfetime = query.Get("begintransfetime")
	endtransfetime = query.Get("endtransfetime")

	beginagentfeeenddate = query.Get("beginagentfeeenddate")
	endagentfeeenddate = query.Get("endagentfeeenddate")

	if collfromtype != "" {
		qcollfromtype := bson.M{"collFromType": collfromtype}
		querySet = append(querySet, qcollfromtype)
	}
	if collno != "" {
		qcollno := bson.M{"collNo": collno}
		querySet = append(querySet, qcollno)
	}
	if collfrom != "" {
		qcollfrom := bson.M{"collFrom": collfrom}
		querySet = append(querySet, qcollfrom)
	}

	if begincolltime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qbegincolltime := bson.M{"collTime": bson.M{"$gte": begincolltime}}
		querySet = append(querySet, qbegincolltime)
	}

	if endcolltime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qendcolltime := bson.M{"collTime": bson.M{"$lte": endcolltime}}
		querySet = append(querySet, qendcolltime)
	}

	if begintransfetime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qtransfetime := bson.M{"transfeTime": bson.M{"$gte": begintransfetime}}
		querySet = append(querySet, qtransfetime)
	}

	if endtransfetime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qtransfetime := bson.M{"transfeTime": bson.M{"$lte": endtransfetime}}
		querySet = append(querySet, qtransfetime)
	}

	if collkind != "" {
		qcollkind := bson.M{"collKind": collkind}
		querySet = append(querySet, qcollkind)
	}
	if collstatus != "" {
		qcollstatus := bson.M{"collStatus": collstatus}
		querySet = append(querySet, qcollstatus)
	}
	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}
	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if beginagentfeeenddate != "" {
		qbegindate := bson.M{"agentFeeEndDate": bson.M{"$gte": beginagentfeeenddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endagentfeeenddate != "" {
		qenddate := bson.M{"agentFeeEndDate": bson.M{"$lte": endagentfeeenddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	if collinfos, err = G_CollMgr.queryDownloadCollbySet(queryBson); err != nil {
		// goto ERR
	}

	outfile = "./downloadfile/coll" + common.BuildDateTodayStr4() + ".xlsx"
	f := xlsx.NewFile()
	sheet, _ := f.AddSheet("clue")
	for idx, _ := range collinfos {
		// fmt.Println(idx)
		//写表头
		// fmt.Println(1111 + idx)
		if idx == 0 {
			// fmt.Println(idx)
			x = collinfos[idx]
			row = sheet.AddRow()
			// reflect.ValueOf(custominfo)
			// v := reflect.ValueOf(&custominfo)
			// n := reflect.ValueOf(&custominfo).NumField()
			t := reflect.TypeOf(x)
			if t.Kind() == reflect.Ptr {
				t = t.Elem()
			}
			// fmt.Println(t.Kind())
			if t.Kind() != reflect.Struct {
				fmt.Println("Check type error not Struct")
				return
			}
			n := t.NumField()
			for i := 0; i < n; i = i + 1 {
				cell := row.AddCell()
				cell.SetValue(t.Field(i).Tag.Get("uname"))
			}
		}

		row = sheet.AddRow()
		collinfo = collinfos[idx]
		row.WriteStruct(collinfo, -1)
	}

	if err = f.Save(outfile); err != nil {
		// goto ERR
	}

	cluemap := make(map[string]interface{})
	// cluemap["cluecount"] = countclue
	// cluemap["filepath"] = outfile[1:]
	cluemap["filepath"] = G_config.FileUrl + ":" + strconv.Itoa(G_config.ApiPort) + "/downloadfile/coll" + common.BuildDateTodayStr4() + ".xlsx"

	if bytes, err = common.BuildResponse(0, "success", cluemap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}

}

func handleCollQuery(resp http.ResponseWriter, req *http.Request) {
	var (
		err   error
		bytes []byte
		// entclueinfo *common.EntClue
		querySet   []bson.M
		skipParam  string
		limitParam string
		skip       int
		limit      int
		collinfos  []*common.Collection
		countcoll  int64
		// rolelimit     *common.RoleLimits

		queryBson bson.M

		collfromtype         string //收款来源类型  订单、客户（用来区分是订单收款还是客户收款）
		collno               string //收款编号  订单编号或者代账客户管理里面的客户编号
		collfrom             string //收款来源 根据订单类别分别显示为：代账客户、注册代账订单、迁入订单、变更订单、注销订单、商标订单、建筑资质订单、其他订单
		collkind             string //收款方式 必选选项，选项分为：建行龙支付、纳川对公、润盈对公、氢数对公、好易标对公、润禾对公、企业支付宝、其他账户
		collstatus           string //转账状态 出纳录入成功显示“出纳已确认”、内账会计角色确认ok则显示“内账会计已确认”
		custommgr            string //客户经理
		accountant           string //主管会计
		beginagentfeeenddate string //代账费开始日期
		endagentfeeenddate   string //代账费结束日期
		begintransfetime     string
		endtransfetime       string
		begincolltime        string
		endcolltime          string
		companyname          string
	)

	query := req.URL.Query()
	collfromtype = query.Get("collfromtype")
	collno = query.Get("collno")
	collfrom = query.Get("collfrom")
	collkind = query.Get("collkind")
	collstatus = query.Get("collstatus")
	accountant = query.Get("accountant")
	custommgr = query.Get("custommgr")
	companyname = query.Get("companyname")
	// colltime = query.Get("colltime")

	begincolltime = query.Get("begincolltime")
	endcolltime = query.Get("endcolltime")

	begintransfetime = query.Get("begintransfetime")
	endtransfetime = query.Get("endtransfetime")

	beginagentfeeenddate = query.Get("beginagentfeeenddate")
	endagentfeeenddate = query.Get("endagentfeeenddate")

	skipParam = query.Get("skip")
	limitParam = query.Get("limit")

	if skip, err = strconv.Atoi(skipParam); err != nil {
		skip = 0
	}

	if limit, err = strconv.Atoi(limitParam); err != nil {
		limit = 100
	}

	if companyname != "" {
		q_companyName := bson.M{"companyName": bson.M{"$regex": companyname, "$options": "$i"}}
		querySet = append(querySet, q_companyName)
	}

	if collfromtype != "" {
		qcollfromtype := bson.M{"collFromType": collfromtype}
		querySet = append(querySet, qcollfromtype)
	}
	if collno != "" {
		qcollno := bson.M{"collNo": collno}
		querySet = append(querySet, qcollno)
	}
	if collfrom != "" {
		qcollfrom := bson.M{"collFrom": collfrom}
		querySet = append(querySet, qcollfrom)
	}

	if begincolltime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qbegincolltime := bson.M{"collTime": bson.M{"$gte": begincolltime}}
		querySet = append(querySet, qbegincolltime)
	}

	if endcolltime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qendcolltime := bson.M{"collTime": bson.M{"$lte": endcolltime}}
		querySet = append(querySet, qendcolltime)
	}

	if begintransfetime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qtransfetime := bson.M{"transfeTime": bson.M{"$gte": begintransfetime}}
		querySet = append(querySet, qtransfetime)
	}

	if endtransfetime != "" {
		// qtransfetime := bson.M{"transfeTime": begintransfetime}

		qtransfetime := bson.M{"transfeTime": bson.M{"$lte": endtransfetime}}
		querySet = append(querySet, qtransfetime)
	}

	if collkind != "" {
		qcollkind := bson.M{"collKind": collkind}
		querySet = append(querySet, qcollkind)
	}
	if collstatus != "" {
		qcollstatus := bson.M{"collStatus": collstatus}
		querySet = append(querySet, qcollstatus)
	}
	if accountant != "" {
		qaccountant := bson.M{"accountant": accountant}
		querySet = append(querySet, qaccountant)
	}
	if custommgr != "" {
		qcustommgr := bson.M{"customMgr": custommgr}
		querySet = append(querySet, qcustommgr)
	}

	if beginagentfeeenddate != "" {
		qbegindate := bson.M{"agentFeeEndDate": bson.M{"$gte": beginagentfeeenddate}}
		querySet = append(querySet, qbegindate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	if endagentfeeenddate != "" {
		qenddate := bson.M{"agentFeeEndDate": bson.M{"$lte": endagentfeeenddate}}
		querySet = append(querySet, qenddate)
		// setElements = append(setElements, bson.E{"createTime", createtime})
	}

	queryBson = bson.M{"$and": querySet}

	collmap := make(map[string]interface{})
	countcoll, _ = G_CollMgr.countCollbySet(queryBson)
	// fmt.Println(countclue)

	if collinfos, err = G_CollMgr.queryCollbySet(queryBson, int64(skip), int64(limit)); err != nil {
		goto ERR
	}
	collmap["collcount"] = countcoll
	collmap["collinfos"] = collinfos
	if bytes, err = common.BuildResponse(0, "success", collmap); err == nil {
		resp.Write(bytes)
	} else {
		goto ERR
	}

	return
ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
}

func (collMgr *CollMgr) delCollById(collid string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		// update *common.HostInfo
		ctx context.Context
		// basecoll  *common.Collection
	)

	_, err = collMgr.CollColl.DeleteOne(ctx, bson.M{"collId": collid})

	return
}

func (collMgr *CollMgr) updConfirmbyCollId(collid string) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		// update *common.HostInfo
		ctx context.Context
		// basecoll  *common.Collection
	)

	_, err = collMgr.CollColl.UpdateOne(ctx, bson.M{"collId": collid}, bson.M{"$set": bson.M{"collStatus": "内账会计已确认"}})

	return
}

func (collMgr *CollMgr) saveColl(coll *common.Collection) (err error) {

	var (
		// resultOne *mongo.InsertOneResult
		// update *common.HostInfo
		ctx context.Context
		// basecoll  *common.Collection
		custom    *common.AgentCustom
		countColl int64
	)

	if coll.CollFromType == "订单" {

	}

	if coll.CollId == "" {
		countColl, err = collMgr.CollColl.CountDocuments(ctx, bson.M{"collNo": coll.CollNo})
		coll.CollId = coll.CollNo + strconv.FormatInt(countColl+1, 10)
		_, err = collMgr.CollColl.InsertOne(context.TODO(), coll)

		if coll.CollFromType == "客户" && coll.AgentFeeEndDate != "" {

			custom = G_CustomMgr.getCustomByNo(coll.CollNo)
			if custom.AgentBeginDate != "" {
				G_CustomMgr.updCustomServerDate(coll.CollNo, coll.AgentFeeEndDate)
			} else {
				G_CustomMgr.updCustomServerAllDate(coll.CollNo, coll.AgentBeginDate, coll.AgentFeeEndDate)
			}
		} else if coll.CollFromType == "订单" && coll.AgentFeeEndDate != "" {

			G_OrderMgr.updOrderServerAllDate(coll.CollNo, coll.AgentBeginDate, coll.AgentFeeEndDate)

			custom = G_CustomMgr.getCustomByOrderNo(coll.CollNo)

			if custom != nil && custom.AgentBeginDate != "" {
				G_CustomMgr.updCustomServerDate(custom.CustomNo, coll.AgentFeeEndDate)
			} else if custom != nil && custom.AgentBeginDate == "" {
				G_CustomMgr.updCustomServerAllDate(custom.CustomNo, coll.AgentBeginDate, coll.AgentFeeEndDate)
			}

		}
	} else {
		// collMgr.CollColl.FindOne(ctx, bson.M{"collId": coll.CollId}).Decode(&basecoll)
		//保留开始的代账日期
		// if basecoll.AgentBeginDate != "" {
		// 	coll.AgentBeginDate = basecoll.AgentBeginDate
		// }
		_, err = collMgr.CollColl.UpdateOne(ctx, bson.M{"collId": coll.CollId}, bson.M{"$set": coll})

		if coll.CollFromType == "客户" {
			custom = G_CustomMgr.getCustomByNo(coll.CollNo)
			if custom.AgentBeginDate != "" {
				G_CustomMgr.updCustomServerDate(coll.CollNo, coll.AgentFeeEndDate)
			} else {
				G_CustomMgr.updCustomServerAllDate(coll.CollNo, coll.AgentBeginDate, coll.AgentFeeEndDate)
			}
		} else if coll.CollFromType == "订单" {
			G_OrderMgr.updOrderServerAllDate(coll.CollNo, coll.AgentBeginDate, coll.AgentFeeEndDate)

			custom = G_CustomMgr.getCustomByOrderNo(coll.CollNo)
			if custom != nil && custom.AgentBeginDate != "" {
				G_CustomMgr.updCustomServerDate(custom.CustomNo, coll.AgentFeeEndDate)
			} else if custom != nil && custom.AgentBeginDate == "" {
				G_CustomMgr.updCustomServerAllDate(custom.CustomNo, coll.AgentBeginDate, coll.AgentFeeEndDate)
			}
		}
		//同步更新订单或者客户的日期
	}

	return
}

func (collMgr *CollMgr) countCollbySet(setElements bson.M) (countColl int64, err error) {
	var (
		// resultOne *mongo.InsertOneResult
		ctx context.Context
		// update *common.HostInfo
	)
	ctx, _ = context.WithTimeout(context.Background(), 15*time.Second)
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		// countColl = 0
		countColl, err = collMgr.CollColl.CountDocuments(ctx, bson.M{})
	} else {
		// fmt.Println(1)
		countColl, err = collMgr.CollColl.CountDocuments(ctx, setElements)
	}
	return
}

func InitCollMgr() (err error) {

	G_CollMgr = &CollMgr{
		client:   G_MongoMgr.client,
		CollColl: G_MongoMgr.MongdbConnect.Collection("collection"),
	}

	return
}

func (collMgr *CollMgr) queryDownloadCollbySet(setElements bson.M) (colls []*common.Collection, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		coll       *common.Collection
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 60*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)
	// findopt.SetLimit(10000)
	// findopt.SetSkip(0)
	findopt.SetBatchSize(3000)

	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = collMgr.CollColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = collMgr.CollColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		coll = &common.Collection{}
		if err = cursor.Decode(coll); err != nil {
			continue
		}
		colls = append(colls, coll)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}

func (collMgr *CollMgr) queryCollbySet(setElements bson.M, skip int64, limit int64) (colls []*common.Collection, err error) {

	var (
		// resultOne *mongo.InsertOneResult
		cursor     *mongo.Cursor
		coll       *common.Collection
		findopt    *options.FindOptions
		ctx        context.Context
		customSort *common.SortById
		// update *common.HostInfo
	)

	ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)

	findopt = &options.FindOptions{}
	customSort = &common.SortById{
		SortOrder: -1,
	}
	findopt.SetSort(customSort)

	if limit > 0 && skip >= 0 {
		findopt.SetLimit(limit)
		findopt.SetSkip(limit * skip)

	} else {
		return
	}
	if len(setElements["$and"].([]primitive.M)) == 0 {
		// fmt.Println(0)
		cursor, err = collMgr.CollColl.Find(context.TODO(), bson.M{}, findopt)
	} else {
		// fmt.Println(1)
		cursor, err = collMgr.CollColl.Find(context.TODO(), setElements, findopt)
	}
	defer cursor.Close(ctx)

	for cursor.Next(ctx) {
		coll = &common.Collection{}
		if err = cursor.Decode(coll); err != nil {
			continue
		}
		colls = append(colls, coll)
	}
	// fmt.Println("doccount:" + strconv.FormatInt(doccount, 10))
	return
}
